<template>
  <div class="app-container">
    <div
      class="col-body"
      :style="{ height: HeightTable + 'px' }"
      v-loading="loading"
    >
      <div class="mx-1" size="large">设备管理</div>
      <div class="blank"></div>
      <el-form
        ref="searchForm"
        inline
        :model="searchRules.form"
        :rules="searchRules.data"
      >
        <div>
          <el-form-item prop="blurry">
            <el-input
              v-model="searchRules.form.blurry"
              placeholder="请输入关键词"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit('searchForm')"
              >搜索</el-button
            >
            <el-button @click="onReset('searchForm')">重置</el-button>
          </el-form-item>
        </div>
        <div>
          <el-form-item>
            <el-button @click="handleAddDevice('add')" type="primary"
              >新增设备</el-button
            >
          </el-form-item>
        </div>
      </el-form>
      <el-table
        :data="tableData"
        style="width: 100%; margin-bottom: 20px"
        :height="HeightTable - 190"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="id" label="ID" width="130" align="center">
        </el-table-column>
        <el-table-column
          prop="name"
          label="设备名称"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="location"
          label="设备地址"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" align="center">
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center">
        </el-table-column>
        <el-table-column align="center" label="操作" width="190">
          <template #default="scope">
            <el-button-group class="ml-4">
              <el-button
                type="primary"
                size="mini"
                @click="handleAddDevice('edit', scope.row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleAddDevice('del', scope.row)"
                >删除</el-button
              >
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px; text-align: center"
        background
        :total="tableTotal"
        :default-page-size="pageSize"
        @current-change="onPageChange"
      />
    </div>
    <el-dialog
      :title="setName"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="DeviceFrom"
        :model="DeviceFrom"
        :rules="DeviceRules"
        label-width="100px"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="DeviceFrom.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备ID" prop="name">
          <el-input v-model="DeviceFrom.id" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备地址" prop="location">
          <el-input
            v-model="DeviceFrom.location"
            placeholder="请输入设备地址"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="DeviceFrom.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  create_device,
  update_device,
  query_device,
  delete_device,
} from "@/api/device";
export default {
  data() {
    return {
      loading: false,
      HeightTable: window.innerHeight - 90,
      pageSize: 10,
      tableTotal: 0,
      tabstatus: false,
      tableData: [],
      searchRules: {
        form: {
          blurry: "",
        },
        data: {},
      },
      open: false,
      setName: "添加设备",
      rowId: null,
      DeviceFrom: {
        name: "",
        location: "",
        remark: "",
        id: "",
      },
      DeviceRules: {
        name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
        location: [
          { required: true, message: "请输入设备地址", trigger: "blur" },
        ],
        remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
      },
      options: [
        {
          value: "设备",
          label: "设备",
        },
        {
          value: "摄像头",
          label: "摄像头",
        },
      ],
    };
  },
  mounted() {
    this.getLogList();
  },
  methods: {
    onPageChange(page) {
      this.getLogList(page);
    },
    handleCiosk(row) {
      this.rowId = row.id;
      this.tabstatus = !this.tabstatus;
    },
    //新增设备
    handleAddDevice(type, row) {
      if (type === "add") {
        this.open = true;
        this.setName = "添加设备";
        Object.keys(this.DeviceFrom).forEach((key) => {
          this.DeviceFrom[key] = "";
        });
      } else if (type === "edit") {
        this.open = true;
        this.rowId = row.id;
        this.setName = "编辑设备";
        this.DeviceFrom.name = row.name;
        this.DeviceFrom.location = row.location;
        this.DeviceFrom.remark = row.remark;
        this.DeviceFrom.id = row.id;
      } else {
        this.$confirm(`此操作将永久删除${row.name}设备, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            delete_device(row.id).then((res) => {
              if (res.status == "success") {
                this.getLogList();
                this.$message({
                  type: "success",
                  message: res.message,
                });
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败!",
                });
              }
            });
          })
          .catch(() => {});
      }
    },
    onReset(refname) {
      this.$refs[refname].resetFields();
      this.getLogList(1);
    },
    onSubmit(refname) {
      this.$refs[refname].validate((valid) => {
        if (valid) {
          switch (refname) {
            case "searchForm":
              let form = this.searchRules.form,
                search = ``;
              for (const name in form) {
                if (form[name] !== "") {
                  search += `&${name}=${form[name]}`;
                }
              }
              this.getLogList(1, search);
              break;
          }
        }
      });
    },
    //需要定时刷新的
    async getLogList(page) {
      page = page ? page : 1;
      this.loading = true;
      query_device(this.pageSize, page)
        .then((res) => {
          this.tableData = res.data;
          this.tableTotal = +res.pagination.total_devices;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    submitForm() {
      this.$refs.DeviceFrom.validate((valid) => {
        if (valid) {
          if (this.setName === "添加设备") {
            delete this.DeviceFrom.device_id;
            create_device(this.DeviceFrom).then((res) => {
              if (res.status == "success") {
                this.$message.success(res.message);
                this.open = false;
                this.getLogList();
              } else {
                this.$message.error(res.message);
              }
            });
          } else {
            this.DeviceFrom.device_id = this.rowId;
            update_device(this.DeviceFrom).then((res) => {
              if (res.status == "success") {
                this.$message.success(res.message);
                this.open = false;
                this.getLogList();
              } else {
                this.$message.error(res.message);
              }
            });
          }
        } else {
          this.$message.error("请填写完整信息");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.col-body {
  .el-form {
    display: flex;
    justify-content: space-between;
  }

  .cell {
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}

.col-body .el-input {
  --el-input-width: 220px;
}

.col-body .el-select {
  --el-select-width: 220px;
}

.blank {
  height: 20px;
}

.blank.line {
  height: auto;
  padding-top: 10px;
  margin-bottom: 10px;
  border-bottom: 1px #ebeef5 solid;
}

.col-body {
  position: relative;
  padding: 20px;
  background: #ffffff;
}

.tree-add {
  position: absolute;
  right: 20px;
}
</style>
